package com.demon.net.handler

import androidx.lifecycle.MutableLiveData
import com.demon.net.ResponseResult
import com.demon.net.ui.UIState

/**
 * 类简要描述
 * <p/>
 * <p>
 * 类详细描述
 * </p>
 *
 * @author zhaozeyang
 * @date 2020/10/15
 */
class DefaultResponseResultHandler(
    private val expired: ((message: String?) -> Unit)? = null,
    private val httpError: ((message: String?) -> Unit)? = null,
    private val failed: ((message: String?, code: Int?) -> Unit)? = null
) : IResponseResultHandler {
  override fun <T : Any>  handle(uiState: MutableLiveData<UIState>, result: ResponseResult<T>, stick:Boolean) {
    when (result) {
      is ResponseResult.Expired -> {
        expired?.invoke(result.message) ?: uiState.postValue(UIState.ExpiredState(result.message).apply { this.stick = stick })
      }
      is ResponseResult.HttpError -> {
        httpError?.invoke(result.exception.message)
            ?: uiState.postValue(UIState.ErrorState("网络异常").apply { this.stick = stick })
      }
      is ResponseResult.Failed -> {
        failed?.invoke(result.exception.errorInfo, result.exception.errorCode)
            ?: uiState.postValue(
                UIState.FailedState(
                    result.exception.errorInfo,
                    result.exception.errorCode
                ).apply {
                  this.stick = stick
                }
            )
      }
      else -> {

      }
    }

  }

}